
import { useState, useEffect, useRef } from 'react';

import { Input, Button, Typography, DatePicker, ConfigProvider, Table, message } from 'antd';
import { UserOutlined, PlusCircleOutlined, DeleteOutlined, CopyOutlined, FormOutlined } from '@ant-design/icons';
// 引入中文语言包-日期选择器
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

import PubSub from 'pubsub-js'
import { showAddProductModal, sendProductData, delProductItem, modifyProductItem } from '../../constant/PubSubKey.js'

//自定义列
import { columns } from '../../constant/productColumn.js'
//自定义组件
import AddProduct from '../../component/addProduct/index.jsx'

//网络
import { generateOrder } from '../../utils/axiosRequest/api.js'

import styles from './index.module.css'

function Main() {
    const [messageApi, contextHolder] = message.useMessage();
    const { Text } = Typography;
    const tableRef = useRef(null); //用于获取表格容器
    const [isModifying, setIsModifying] = useState(false); // 添加修改标志位
    // 设置dayjs使用中文
    dayjs.locale('zh-cn');
    //表格展示数据
    const [showDataSource, setDataSource] = useState([]);
    const [customerAddress, setCustomerAddress] = useState('')//客户地址
    const [deliveryTime, setDeliveryTime] = useState('')//送货时间
    const [handlerPerson, setHandlerPerson] = useState('')//经办人
    const [printBtnLoadState, setPrintBtnLoadState] = useState(false)//打印按钮加载状态

    // []空数组相当于componentDidMount
    useEffect(() => {
        const token = PubSub.subscribe(sendProductData, addProductDataSubscriber)//订阅消息
        const token1 = PubSub.subscribe(delProductItem, delProductItemSubscriber)//订阅消息
        const token3 = PubSub.subscribe(modifyProductItem, modifyProductItemSubscriber)//订阅消息
        return () => {
            PubSub.unsubscribe(token);//解绑消息
            PubSub.unsubscribe(token1);//解绑消息
            PubSub.unsubscribe(token3);//解绑消息
        }
    }, []);

    // 监听数据变化，自动滚动到底部
    useEffect(() => {
        if (tableRef.current && showDataSource.length > 0) {
            //修改操作不滚动
            if (isModifying) {
                return;
            }
            // 使用 setTimeout 确保在 DOM 更新后执行
            setTimeout(() => {
                // 方法1：直接查找 antd 表格的滚动区域
                const tableBody = document.querySelector('.ant-table-body');
                if (tableBody) {
                    tableBody.scrollTop = tableBody.scrollHeight;
                    return;
                }
            }, 500);
        }
    }, [showDataSource, isModifying]); // 依赖 showDataSource 的变化

    //接收订阅的消息
    const addProductDataSubscriber = function (msg, productData) {
        setIsModifying(false);// 设置修改标志位
        setDataSource(prevData => {
            // 获取当前最大序号，确保删除数据后序号仍然连续
            const maxSerial = prevData.length > 0 ? Math.max(...prevData.map(item => item.serial)) : 0;
            const newItem = {
                key: productData.id, // tab控件必要属性
                serial: maxSerial + 1, // 基于最大序号+1
                productName: productData.productName,
                productUnit: productData.productUnit,
                productQuantity: productData.productQuantity,
                productPrice: productData.productPrice,
                productRemarks: productData.productRemarks,
                action: productData,
            };
            return [...prevData, newItem]; // 追加新项目到数组末尾
        });
    };

    //接收订阅的消息
    const modifyProductItemSubscriber = function (msg, data) {
        setIsModifying(true);// 设置修改标志位
        const id = data.id;
        setDataSource(prevData => {
            const newDataSource = [...prevData];
            const index = newDataSource.findIndex(item => item.key === id);
            if (index !== -1) {
                //旧数组
                const originalItem = newDataSource[index];
                newDataSource[index] = {
                    key: originalItem.key,
                    serial: originalItem.serial,
                    productName: data.productName,
                    productUnit: data.productUnit,
                    productQuantity: data.productQuantity,
                    productPrice: data.productPrice,
                    productRemarks: data.productRemarks,
                    action: data,
                };
            }
            return newDataSource;
        });
    };

    //接收订阅的消息
    const delProductItemSubscriber = function (msg, data) {
        setIsModifying(true);// 设置修改标志位
        const id = data.id;
        setDataSource(prevData => prevData.filter(item => item.key !== id));
    };

    function addProduct() {
        const length = showDataSource.length
        if (length >= 9) {
            messageApi.error('货物数量不能超过9条');
        } else {
            PubSub.publish(showAddProductModal, {});
        }
    }

    function reloadProduct() {
        messageApi.success('货物已清空');
        setDataSource([]);
    }

    // 打印货单
    function printList() {
        if (printBtnLoadState) {
            messageApi.error('正在打印中，请稍后...');
            return;
        }
        setPrintBtnLoadState(true)
        const params = new Map()
        params.set('customerAddress', customerAddress);
        params.set('deliveryTime', deliveryTime);
        params.set('productList', showDataSource);
        params.set('handlerPerson', handlerPerson);
        generateOrder(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    const repsData = data.data
                    const pdfName = repsData.pdfName//拿到文件名
                    window.open('http://localhost:9010/preview/' + pdfName, '_blank');
                } else {
                    //处理失败
                    messageApi.error(data.des)
                }
                setPrintBtnLoadState(false)
            })
            .catch(error => {
                messageApi.error(error.message)
                setPrintBtnLoadState(false)
            });
    }

    function onChangeCustomerAddress(val) {
        let customerAddress = val.target.value
        setCustomerAddress(customerAddress);
    }

    function onChangeHandlerPerson(val) {
        let handlerPerson = val.target.value
        setHandlerPerson(handlerPerson);
    }

    const onDatePickerChange = (date, dateString) => {
        setDeliveryTime(dateString)
    };

    return (
        <ConfigProvider locale={zhCN}>
            {contextHolder}
            <AddProduct></AddProduct>
            <div className={styles.root_box} >
                <div className={styles.mian_box} >
                    <div className={styles.customer_address_box}>
                        <Text strong>客户地址：</Text>
                        <Input onChange={onChangeCustomerAddress} value={customerAddress} className={styles.inp_customer_address}
                            placeholder='请输入客户地址' allowClear={true} prefix={<UserOutlined />} size="large" />
                        <Text className={styles.text_customer_address} strong>制单人：</Text>
                        <Input onChange={onChangeHandlerPerson} value={handlerPerson} className={styles.inp_handler_person}
                            placeholder='请输入制单人' allowClear={true} prefix={<FormOutlined />} size="large" />
                        <Text className={styles.text_customer_address} strong>送货日期：</Text>
                        <DatePicker placeholder={'请选择送货日期'} onChange={onDatePickerChange} size={"large"} />
                    </div>
                    <div className={styles.operation_box}>
                        <Button className={styles.btn_add_product} icon={<PlusCircleOutlined />} onClick={addProduct} type="primary">增加货物</Button>
                        <Button className={styles.btn_reload_product} icon={<DeleteOutlined />} onClick={reloadProduct} type="primary" danger>清空货物</Button>
                    </div>
                    <Table ref={tableRef} className={styles.tab_product_data} pagination={false} bordered={true}
                        size='large' dataSource={showDataSource} columns={columns} scroll={{ y: 55 * 7 }} />
                    <div className={styles.print_box}>
                        <Button loading={printBtnLoadState} onClick={printList} className={styles.btn_print_product} icon={<CopyOutlined />} type="primary">打印货单</Button>
                    </div>
                </div>
            </div>
        </ConfigProvider>
    )
}

export default Main;